package comtgl.demo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.security.SecureRandom;
import java.util.Base64;
import java.util.Calendar;
import java.util.HashMap;

public class JWTUtils {
//    public static String generateRandomKey(int bitStrength) {
//        byte[] keyBytes = new byte[bitStrength / 8];
//        new SecureRandom().nextBytes(keyBytes);
//        return Base64.getEncoder().encodeToString(keyBytes);
//    }
    public static final String SECRET = "IUF9YDm4JlBndUaBnv02sYoa1JyDpp0oLuYZzZszoTs=";
    public static void main(String[] args) {
//        String randomKey = generateRandomKey(256);
        String token = makeToken();
        System.out.println(token);
        parseToken(token);
    }
    public static String makeToken() {

        HashMap<String, Object> map = new HashMap<>();
        Calendar instance = Calendar.getInstance();
        // 20秒后令牌token失效
        instance.add(Calendar.SECOND,2);

        String token = JWT.create()
                .withHeader(map) // header可以不写，因为默认值就是它
                .withClaim("userId", 21)  //payload
                .withClaim("token", "xiaoshuang")
                .withExpiresAt(instance.getTime()) // 指定令牌的过期时间
                .sign(Algorithm.HMAC256(SECRET));//签名

        return token;
    }

    public static void parseToken(String token){
        // 通过签名生成验证对象
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();

        DecodedJWT verify = jwtVerifier.verify(token);
        System.out.println(verify.getClaim("userId"));
        System.out.println(verify.getClaim("token"));
        System.out.println("令牌过期时间："+verify.getExpiresAt());

    }


}
